package com.gamelife.web.service;

import com.gamelife.web.domain.LoginUser;
import com.gamelife.web.domain.UserState;
import com.gamelife.web.domain.entity.SysUser;
import com.gamelife.web.exception.BaseException;
import com.gamelife.web.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 用户验证处理
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 数据库查询用户信息
        SysUser sysUser = sysUserService.selectUserByUserName(username);
        log.info("当前登录用户 = {}",sysUser.toString());

        if (Objects.isNull(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        } else if (UserState.DELETED.getCode().equals(sysUser.getState())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserState.DISABLE.getCode().equals(sysUser.getState())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        // 数据库查询权限信息
        Set<String> permission= sysMenuService.selectPermissionByUserId(sysUser.getId());

        return new LoginUser(sysUser, permission);
    }
}
